package com.juzipi.rabbit.service;

import com.juzipi.rabbit.config.DirectConfig;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.mail.MailProperties;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.time.Duration;
import java.time.LocalDateTime;

/**
 * @Author juzipi
 * @Date 2021/7/17 17:56
 * @Info
 */
@Service
public class MailService {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private MailProperties mailProperties;
    @Autowired
    private JavaMailSender javaMailSender;

    public static final long s = 1000;
    public static final long m = s*60;



    //即时发送
    public void send(String mail){
        String s = this.sendHtml(mail);
        DirectConfig directConfig = new DirectConfig();
        DirectExchange directExchange = directConfig.mailExchange();
        String routingKey = directConfig.bindingMailQueue().getRoutingKey();
        String name = directExchange.getName();
        rabbitTemplate.convertAndSend(name,routingKey,s);
    }


    public void sendDelay(Integer time){
//        String s = this.sendHtml(mail);
        DirectConfig directConfig = new DirectConfig();
        DirectExchange directExchange = directConfig.mailExchange();
        String routingKey = directConfig.bindingMailQueue().getRoutingKey();
        String name = directExchange.getName();
        rabbitTemplate.convertAndSend(name,routingKey,"发送邮件",message -> {
            //估计单位是毫秒
            message.getMessageProperties().setExpiration(String.valueOf(time * 1000 * 60));
            return message;
        });
    }




    public String sendHtml(String mail) {
        try {
            MimeMessage mimeMessage = javaMailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
            helper.setFrom(mailProperties.getUsername());//发送方
            helper.setTo(mail);//接收方邮箱
            helper.setSubject("测试rabbitmq");//主题
            helper.setText("<h1>你好你好你好</h1>",true);//内容
            javaMailSender.send(mimeMessage);
            return "发送成功";
        } catch (MessagingException e) {
            throw new RuntimeException();
        }
    }


}
